package com.thinqq.tracktask.client;

import java.util.ArrayList;
import java.util.List;


import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;

/**
 * This class wrapps all the Async requests from client side
 * @author rakesh
 *
 */
public class TrackTaskRequestEngine {

	public interface Observer {
		void executeDisplay(Object...cbj);
	}

	private static TrackTaskRequestEngine instance;
	
	/**
	 * Create a remote service proxy to talk to the server-side task service
	 */
	private final TaskServiceAsync taskService = GWT.create(TaskService.class);

	private List<Observer> taskObserver = new ArrayList<TrackTaskRequestEngine.Observer>();
	
	private TrackTaskRequestEngine(){
		
	}

	public static TrackTaskRequestEngine getInstance() {
		if(instance==null){
			instance = new TrackTaskRequestEngine();
		}
		return instance;
	}

	public void executeGetTaskList() {
		
		taskService.getTaskList(new AsyncCallback<List<String>>() {

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onSuccess(List<String> result) {
				for (Observer obs : taskObserver) {
					obs.executeDisplay(result);
				}
			}
		});
		
	}

	public void addTaskListObserver(Observer obs) {
		taskObserver.add(obs);
	}

	public void executeAddTask(String textToServer) {
		taskService.addTask(textToServer, new AsyncCallback<Void>() {

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onSuccess(Void result) {
				executeGetTaskList();
			}
		});
	}
}
